//
//  AllViewController.m
//  XiangMuB
//
//  Created by 999999999999 on 16/8/14.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "AllViewController.h"
#import "UIView+BSFrame.h"
#import "Content.h"
#import "CycleView.h"
#import "LMJNetWorkRequestManager.h"
#import "AllModel.h"
#import "AllViewCell.h"
#import "URL_HeaderDefine.h"
#import <MJRefresh.h>
#import "ImageArrayModel.h"
#import "UIImageView+WebCache.h"
#import "WebViewController.h"
//#import <AFNetworking+RXHeader.h>
@interface AllViewController ()<UIScrollViewDelegate>
//轮播图属性
@property (nonatomic,strong) CycleView *cycleView;
//
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,assign) NSInteger time;
/**
 *  轮播图数组
 */
@property (nonatomic,strong) NSMutableArray *imageArray;
/**
 *  轮播图
 */
@property (nonatomic,strong) UIScrollView *lunboScrollView;
/**
 *  图片个数
 */
@property (nonatomic,assign) NSInteger imageNumber;
/**
 *  pageController页码
 */
@property (nonatomic,strong)UIPageControl *myPageControl;
/**
 * 索引,图片计数器
 */
@property (nonatomic, assign) NSInteger currentIndex;
/**
 *  计时器
 */
@property (nonatomic, strong) NSTimer *myTimer;

@end

static NSString *NEWUrl = @"http://c.m.163.com/nc/article/headline/T1348647909107/";
static NSString *NEWUrl1 = @"-20.html";
@implementation AllViewController

- (NSMutableArray *)imageArray {
    if (_imageArray == nil) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}

-(NSMutableArray *)dataArray {
    if (_dataArray == nil) {
        _dataArray =[[NSMutableArray alloc]init];
    }
    return _dataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    [self setUpTable];
    self.time = 0;
    //注册
    [self.tableView registerNib:[UINib nibWithNibName:@"AllViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    [self setUpRefresh];
}
#pragma mark----初始化tableview
-(void)setUpTable{

    //  设置内边距
    CGFloat bottom = self.tabBarController.tabBar.height;
    CGFloat top =TitlesViewY +TitlesViewH;
    self.tableView.contentInset = UIEdgeInsetsMake(top, 0, bottom, 0);
    self.tableView.backgroundColor = [UIColor clearColor];
    //设置滚动条内边距
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    //分割线
    self.tableView.separatorStyle = UITableViewRowAnimationNone;
    self.tableView.backgroundColor = [UIColor clearColor];
    
//    [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
    
}

#pragma mark----刷新数据
-(void)setUpRefresh{
    //下拉刷新,在主线程结束刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewTopic)];
    //    根据拖拽比例自动改变透明度
    self.tableView.header.autoChangeAlpha = YES;
    //进入页面自动刷新
    [self.tableView.mj_header beginRefreshing];
    //下拉刷新,加载更多数据
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTopic)];
    
}

#pragma mark --第一次获取数据
- (void)loadNewTopic {
    
    [self.tableView.mj_footer endRefreshing];
    self.time = 0;
    __weak typeof(self)weakSelf = self;
    NSString *urlStr = [NSString stringWithFormat:@"%@%ld%@", NEWUrl, self.time, NEWUrl1];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    
    NSURLSession *session = [NSURLSession sharedSession];//系统提供全局的单利
    
    //3创建task任务执行对象
    NSURLSessionTask *sessionTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (error == nil) {
            [weakSelf.dataArray removeAllObjects];
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//            NSLog(@"%@",dict);
            NSArray *arrayarray = dict[@"T1348647909107"];
            NSMutableArray *array = arrayarray.mutableCopy;
//            NSLog(@"......%@", array);
#pragma mark ---获取轮播图
            [weakSelf.imageArray removeAllObjects];
            NSDictionary *imageDic = array[0];
            for (NSDictionary *arr in imageDic[@"ads"]) {
                // 创建一个model
                ImageArrayModel *imageModel = [[ImageArrayModel alloc]init];
                // 使用KVC 赋值
                [imageModel setValuesForKeysWithDictionary:arr];
                // 添加到属性数组中存放数据
                [weakSelf.imageArray addObject:imageModel];
                
            }
            [array removeObjectAtIndex:0];
            
            for (NSDictionary *dict in array) {
                AllModel *model = [[AllModel alloc]init];
                [model setValuesForKeysWithDictionary:dict];
//                NSLog(@"%@", model);
                [weakSelf.dataArray addObject:model];
            }
            
            
            
#pragma mark----刷新视图
            dispatch_async(dispatch_get_main_queue(), ^{
                //结束刷新
                [weakSelf.tableView.mj_header endRefreshing];
                weakSelf.time += 20;
                
                NSMutableArray *imageAr = [NSMutableArray array];
                
                for (ImageArrayModel *model in weakSelf.imageArray) {
                    [imageAr addObject:model.imgsrc];
                }
                
                
                weakSelf.lunboScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, weakSelf.view.bounds.size.width, 250)];
                
//                _lunboScrollView.backgroundColor = [UIColor redColor];
                //关闭屏幕回弹效果
                _lunboScrollView.bounces= NO;
                //关闭滚动条
                _lunboScrollView.showsHorizontalScrollIndicator = NO;
                _lunboScrollView.pagingEnabled = YES;
                weakSelf.tableView.tableHeaderView = _lunboScrollView;
                weakSelf.imageNumber = imageAr.count;
                for (int i = 0; i < imageAr.count; i++) {
//                    NSLog(@"==--==%@", imageAr[i]);
                    UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(i * weakSelf.view.bounds.size.width, 0, weakSelf.view.bounds.size.width, 250)];
                    [image sd_setImageWithURL:imageAr[i]];
                    _lunboScrollView.contentSize = CGSizeMake((i + 1) * weakSelf.view.bounds.size.width, 250);
                    _lunboScrollView.delegate = self;
                    [_lunboScrollView addSubview:image];
#pragma mark----MyPageControl
                    [self pageControl];
//
                    
                }
                [weakSelf.tableView reloadData];
                
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                //结束刷新
                [weakSelf.tableView.mj_header endRefreshing];
            });
        }
    }];
    //执行
    [sessionTask resume];
}

#pragma mark ---获取更多
- (void)loadMoreTopic {
    [self.tableView.mj_header endRefreshing];
    __weak typeof(self)weakSelf = self;
    NSString *urlStr = [NSString stringWithFormat:@"%@%ld%@", NEWUrl, self.time, NEWUrl1];
    
    NSURL *url = [NSURL URLWithString:urlStr];
    
    
    NSURLSession *session = [NSURLSession sharedSession];//系统提供全局的单利
    
    //3创建task任务执行对象
    NSURLSessionTask *sessionTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            self.time += 20;
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        NSArray *arrayarray = dict[@"T1348647909107"];
        NSMutableArray *array = arrayarray.mutableCopy;
#pragma mark ---获取轮播图
        [weakSelf.imageArray removeAllObjects];
        NSDictionary *imageDic = array[0];
        for (NSDictionary *arr in imageDic[@"ads"]) {
            ImageArrayModel *imageModel = [[ImageArrayModel alloc]init];
            [imageModel setValuesForKeysWithDictionary:arr];
            [weakSelf.imageArray addObject:imageModel];
            
        }
        [array removeObjectAtIndex:0];
        for (NSDictionary *dict in array) {
            AllModel *model = [[AllModel alloc]init];
            [model setValuesForKeysWithDictionary:dict];
            [weakSelf.dataArray addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //结束刷新
            [weakSelf.tableView.mj_footer endRefreshing];
            [weakSelf.tableView reloadData];
            
        });
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            //结束刷新
            [weakSelf.tableView.mj_footer endRefreshing];
        });
    }
    }];
    //执行
    [sessionTask resume];
}


#pragma mark ---创建pageControl
-(void)pageControl{

    self.myPageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(200, 220, 200, 20)];

    self.myPageControl.numberOfPages=self.imageNumber;
    self.myPageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
    self.myPageControl.currentPageIndicatorTintColor = [UIColor darkGrayColor];
    [self.myPageControl addTarget:self action:@selector(pageAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:self.myPageControl];
    self.myPageControl.currentPage = self.currentIndex;
////    添加计时器
//    self.myTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(moveToNextPage) userInfo:nil repeats:YES];
//    [[NSRunLoop mainRunLoop]addTimer:self.myTimer forMode:NSRunLoopCommonModes];
    
}
-(void)pageAction{
    [self.lunboScrollView setContentOffset:CGPointMake(self.view.bounds.size.width *(self.myPageControl.currentPage), 0) animated:YES];
}
//-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
//    [self.myTimer invalidate];
//    self.myTimer =nil;
//}
//-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
//    self.myTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(moveToNextPage) userInfo:nil repeats:YES];
//    [[NSRunLoop mainRunLoop]addTimer:self.myTimer forMode:NSRunLoopCommonModes];
//}
//

-(void)moveToNextPage{

    [self.lunboScrollView setContentOffset:CGPointMake(self.myPageControl.currentPage * self.view.bounds.size.width, 0) animated:YES];
}
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return [self.lunboScrollView viewWithTag:self.myPageControl.currentPage +1];
}
-(void)scrollViewDidZoom:(UIScrollView *)scrollView{
    [self.lunboScrollView viewWithTag:self.myPageControl.currentPage +1].center = self.view.center ;
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    self.myPageControl.currentPage = (self.lunboScrollView.contentOffset.x +self.view.bounds.size.width*0.5)/self.view.bounds.size.width;
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    self.myPageControl.currentPage = self.lunboScrollView.contentOffset.x/self.view.bounds.size.width;
    for (UIScrollView *sView in self.lunboScrollView.subviews) {
        if ([sView isKindOfClass:[UIScrollView class]]) {
            sView.zoomScale = 1;
        }
    }
}


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AllViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (cell == nil) {
        cell = [[AllViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"cell"];
    }
 
    AllModel *model = self.dataArray[indexPath.row];
    cell.model = model;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 118;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    WebViewController *webVC = [[WebViewController alloc]init];
    webVC.urlStr = [self.dataArray[indexPath.row] url_3w];
    [self.navigationController pushViewController:webVC animated:YES];
}


@end